import 'package:sow_app_core/src/entity/user.dart';
import 'package:sow_app_core/src/error/exception.dart';
import 'package:sow_app_core/src/usecase/token_usecase.dart';
import 'package:sow_app_core/src/usecase/usecase.dart';
import 'package:sow_app_core/src/usecase/user_usecase.dart';
import 'package:test/test.dart';

import 'package:sow_app_mock/sow_app_mock.dart';

void main() {
  group('user usecase test group', () {
    final restClient = MockRestClient();
    final userRepository = MockUserRepository(restClient);
    test(
      "should return id == -1 when get User.empty",
      () async {
        // arrange

        // act
        // assert
        expect(User.empty.userId, -1);
      },
    );
    test(
      "should return null when called GetUserUseCase() with empty token",
      () async {
        // arrange

        restClient.setAuthorization('404');
        final usecase = GetUserUseCase(userRepository);
        User? user;
        // act
        try {
          user = await usecase(NoParams());
        } on UserNotfoundException {
          expect(user, isNull);
        }
        // assert
      },
    );
    test(
      "should return valid token after called LoginUseCase() and called GetTokenUseCase()",
      () async {
        // arrange
        restClient.setAuthorization('666');
        final usecase = LoginUseCase(userRepository);
        // act
        final token = await usecase(
            LoginParam('17612345678', '17612345678', 'code', 'uuid'));

        await SetTokenUseCase(MockTokenRepository(), MockRestClient())(token);
        // assert
        expect(token.length, 184);
      },
    );
    test(
      "should return user when called GetUserUseCase() with valid token",
      () async {
        // arrange
        final usecase = GetUserUseCase(userRepository);
        // act
        final user = await usecase(NoParams());
        // assert
        expect(user, isA<User>());
        expect(user.userId, 5);
      },
    );

    test(
        "should return ServerException when called RegisterUseCase() with exist username",
        () async {
      // arrange
      final usecase = RegisterUseCase(userRepository);
      // act
      try {
        await usecase(RegisterParam('17612345678', '17612345678Aa', '666'));
      } on ServerException catch (e) {
        // assert
        expect(e.msg, '新增用户\'17612345678\'失败，登录账号已存在');
      }
    });
  });
}
